import re
import yaml
from datetime import datetime, timedelta
from openpyxl import Workbook
from openpyxl.styles import Alignment

with open('formateData/config.yaml', 'r') as f:
    config = yaml.safe_load(f)
timeRangeList = config['timeRange']

# startTime = datetime.strptime(config['timeRange'], '%H:%M:%S.%f').time()
# endTime = (datetime.combine(datetime.min, startTime) + timedelta(minutes=config['timeGap'])).time()
anchorList = config['anchorList']
# timeGap = config['timeGap']
anchorNum = config['anchorNum']
filePath = config['filePath']


class TimeRange:
    startTime=None
    endTime=None
    def __init__(self,startTime,endTime):
        self.startTime = startTime
        self.endTime = endTime
myTimeRangeList =  []
for i in range(len(timeRangeList)):
    split_result = timeRangeList[i].split("-")
    startTime = datetime.strptime(split_result[0], '%H:%M:%S').time()
    endTime = datetime.strptime(split_result[1], '%H:%M:%S').time()
    myTimeRangeList.append(TimeRange(startTime, endTime))




num_dict = {}
dist_dict = {}
res_dist = {}
for anchor in anchorList:
    num_dict[anchor] = 0
    dist_dict[anchor] = []
    res_dist[anchor] = 0

def add_num_to_time(time_obj, minutes, seconds):
    delta = timedelta(minutes=minutes, seconds=seconds)
    new_time_obj = (datetime.combine(datetime.min, time_obj) + delta).time()
    return new_time_obj


workbook = Workbook()
worksheet = workbook.active

with open(filePath, "r") as file:
    data = file.read()
lines = data.splitlines()
worksheet.append(["时间", "距离", "Anchor", "出现次数", "出现0次数", "时间差(s)", "收到串口信息概率"])

k = 0
sourceData = []
for line in lines:
    if line != '':
        split = line.split("?????")
        time = re.findall(r'\[(\d+:\d+:\d+\.\d+)\]', split[0])
        data = re.findall(r'([A-Z0-9]+)\[(-?\d+\.\d+,-?\d+\.\d+,-?\d+\.\d+)\]=(\d+\.\d+)', split[1])
        for i in range(len(data)):
            my_tuple = ()
            my_tuple = (time[0], data[i][0], data[i][2])
            sourceData.insert(k, my_tuple)
            k += 1
def appendToFile():
    global value, time
    num = 0
    for key, value in dist_dict.items():
        value = [float(x) for x in value]
        for e in value:
            if e == 0:
                num += 1
        if len(value) > 2:
            value.remove(min(value))
            value.remove(max(value))
        average = sum(value) / len(value)
        res_dist[key] = average
    time = startTime.strftime("%H:%M:%S.%f")[:-3] + '-' + endTime.strftime("%H:%M:%S.%f")[:-3]
    for key, value in num_dict.items():
        secondGap = (endTime.hour - startTime.hour) * 3600 + (endTime.minute - startTime.minute) * 60 + (
                endTime.second - startTime.second)
        rate = round(value / secondGap * 100, 2) if round(value / secondGap * 100, 2) < 100 else 100
        worksheet.append(
            [time, round(res_dist[key], 3), key, value, num, secondGap, str(rate) + '%'])


def pollTimeRange(start,end):
    global i, anchor
    for i in range(len(sourceData)):
        currentTime = datetime.strptime(sourceData[i][0], '%H:%M:%S.%f').time()
        if currentTime >= start and currentTime <= end:
            anchor = sourceData[i][1]
            if anchor not in dist_dict:
                dist_dict[anchor] = []
                num_dict[anchor] = 0
            dist_dict[anchor].append(sourceData[i][2])
            num_dict[anchor] += 1
    appendToFile()
    worksheet.append([])
    dist_dict.clear()
    num_dict.clear()
    res_dist.clear()


for j in range(len(myTimeRangeList)):
    startTime = myTimeRangeList[j].startTime
    endTime = myTimeRangeList[j].endTime
    pollTimeRange(startTime,endTime)

for row in worksheet.iter_rows():
    for cell in row:
        cell.alignment = Alignment(horizontal='center', vertical='center')

workbook.save("output.xlsx")
